package com.thoughtservice.jspdoc.json;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;
import com.thoughtservice.jspdoc.DirTree;
import com.thoughtservice.jspdoc.JSPFileList;
import com.thoughtservice.jspdoc.JSPPage;
import com.thoughtservice.jspdoc.RE;
import com.thoughtservice.jspdoc.RESyntaxException;
import com.thoughtservice.jspdoc.utils.ProcessorUtils;

public class JSONGenerator {

	private final static Logger LOG = LoggerFactory
			.getLogger(JSONGenerator.class);
	private Gson gson;
	private String json;

	// Generate a JSON object for D3 to render
	// var myjson = '{"name" : "user-form.jsp", "children" : [{"name" :
	// "company-template", "children": [{"name" :
	// "pages/tiles/common-layout.jsp"}]}, {"name" : "user-body-as-tile",
	// "children": [{"name" : "pages/user/body/user-form-body.jsp"}]} ]}';

	public JSONGenerator(JSPPage p, String jspName,
			Iterator<String> tileInserts, Iterator<File> staticIncludes,
			Iterator<File> dynamicIncludes, JSPFileList jspFileList) {
		LOG.trace("Entering {}", "JSONGenerator");
		gson = new Gson();

		// JSP or JSPF Name
		Data data = new Data(jspName);

		List<Data> fileList = new ArrayList<Data>();

		while (tileInserts.hasNext()) {
			String tileName = (String) tileInserts.next();
			File l = (File) p.getTileInPath(tileName);
			String lName = l.toString();
			lName = lName.replace('\\', '/');
			LOG.debug("tileName --> {} path --> ", tileName, lName);

			// Tiles insertions
			List<Data> children = new ArrayList<Data>();
			if("".equals(tileName)){
				tileName = "Tile Inserts";
			}				
			Data d1 = new Data(tileName, children);
			children.add(new Data(lName, null));
			d1.setChildren(children);

			fileList.add(d1);
		}
		// Static Include
		while (staticIncludes.hasNext()) {
			File l = (File) staticIncludes.next();
			String lName = l.toString();
			JSPPage dst = ProcessorUtils.getPage(lName, jspFileList);
			lName = lName.replace('\\', '/');

			if (lName.length() > DirTree.rootSourceDir.length()) {
				String justName = lName.substring(
						DirTree.rootSourceDir.length() + 1, lName.length());

				// String fullName =
				// lName.substring(DirTree.rootSourceDir.length(),
				// lName.length());
				// System.out.println(fullName);
				RE re;
				String justHTMLName;
				try {
					re = new RE("\\.jsp$");
					justHTMLName = re.subst(justName, ".html");
					String pageDesc = "EMPTY DESC";
					// Add for JSON object
					List<Data> children = new ArrayList<Data>();
					if (dst != null) {
						pageDesc = dst.getPageDescShort();
						if ("".equals(pageDesc)) {
							pageDesc = "Statically Included as " + justHTMLName;
						} else {
							pageDesc = dst.getPageDescShort() + justHTMLName;
						}
					}
					Data d1 = new Data(pageDesc, children);
					children.add(new Data(lName, null));
					d1.setChildren(children);

					fileList.add(d1);
				} catch (RESyntaxException e) {					
					LOG.error("{}", ExceptionUtils.getFullStackTrace(e));
				}
			} else {
				LOG.debug("**********SKIPPING LINK");
			}
		}

		// Dynamic Include
		while (dynamicIncludes.hasNext()) {
			File l = (File) dynamicIncludes.next();
			String lName = l.toString();
			JSPPage dst = ProcessorUtils.getPage(lName, jspFileList);
			lName = lName.replace('\\', '/');

			if (lName.length() > DirTree.rootSourceDir.length()) {
				String justName = lName.substring(
						DirTree.rootSourceDir.length() + 1, lName.length());

				// String fullName =
				// lName.substring(DirTree.rootSourceDir.length(),
				// lName.length());
				// System.out.println(fullName);
				RE re;
				String justHTMLName;
				try {
					re = new RE("\\.jsp$");
					justHTMLName = re.subst(justName, ".html");

					// Add for JSON object
					List<Data> children = new ArrayList<Data>();
					String pageDesc = "EMPTY DESC";
					if (dst != null) {
						pageDesc = dst.getPageDescShort();
						if ("".equals(pageDesc)) {
							pageDesc = "Dynamically Included as "
									+ justHTMLName;
						} else {
							pageDesc = dst.getPageDescShort() + justHTMLName;
						}
					}

					Data d1 = new Data(pageDesc, children);
					children.add(new Data(lName, null));
					d1.setChildren(children);

					fileList.add(d1);
				} catch (RESyntaxException e) {
					// TODO Auto-generated catch block
					LOG.error("{}", ExceptionUtils.getFullStackTrace(e));
				}
			} else {
				LOG.debug("**********SKIPPING LINK");
			}
		}

		/*
		 * List<Data> childrend2 = new ArrayList<Data>(); Data d2 = new
		 * Data("user-body-as-tile", children); childrend2.add(new
		 * Data("pages/user/body/user-form-body.jsp",null));
		 */

		// fileList.add(d2);

		data.setChildren(fileList);

		json = gson.toJson(data);

		// System.out.println("{\"name\":\"user-form.jsp\",\"children\":[{\"name\":\"company-template\",\"children\":[{\"name\":\"pages/tiles/common-layout.jsp\"}]},{\"name\":\"user-body-as-tile\",\"children\":[{\"name\":\"pages/user/body/user-form-body.jsp\"}]}]};");
		LOG.debug("JSON Generated data is {}", json);

	}

	public static void main(String[] args) {
		// new JSONGenerator("test");
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}
}
